package com.niit.order.web;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.io.FileNotFoundException;
import java.io.IOException;


/**
 * 01.定义服务降级 及 最终降级方法
 * 02.异常捕获
 * 03.异常忽略的设置
 *
 * @author yaojianfeng
 */
@RestController
@RequestMapping("/consumer")
public class HystrixConsumerController01 {
    @Autowired
    private RestTemplate restTemplate;


    /**
     * 测试 HystrixCommand注解各种属性
     *
     * @param param
     * @return
     */
    @GetMapping("/hystrix/demo1/{param}")
    @HystrixCommand(fallbackMethod = "showAppInfoFallback",
            ignoreExceptions = {IOException.class, FileNotFoundException.class}
    )
    public String showAppInfo(@PathVariable("param") String param) {
        //模拟404情况
        String url = "http://userservice/provider/hystrix/" + param;
        return restTemplate.getForObject(url, String.class);
    }


    /**
     * 服务降级方法
     *
     * @param param     源方法传入的参数
     * @param exception 接收到的异常信息
     * @return 和源方法的返回值类型保持一致
     */
    @HystrixCommand(fallbackMethod = "showAppInfoFinalFallback")
    public String showAppInfoFallback(String param, Throwable exception) {
        System.out.println(exception.getMessage());
        String url = "http://userservice/hystrix/byParam/" + param;
        return restTemplate.getForObject(url, String.class);

//        return "服务器繁忙,请稍后再试o(╥﹏╥)o" + param;
    }


    /**
     * 终极服务降级方法
     *
     * @param param 源方法传入的参数
     * @return 和源方法的返回值类型保持一致
     */

    public String showAppInfoFinalFallback(String param,Throwable exception) {

        return "最终降级方法,逻辑稳定..." + param + " exception: " + exception;
    }

}
